<?php

    include("conn.php");

    $t1 = microtime(true);

    $uid=$_REQUEST ["uid"]; ///  uid自己。 以后要换token _GET  _POST

    $to=$_REQUEST ["to"];

    $desc=$_REQUEST ["desc"];


//是否已经是好友了。
function is_friend(&$conn,  &$uid , &$fid )
{ 

    $sql="select * from tb_friend where uid=$uid and fid=$fid "; 

	// 执行sql查询
	if( getRecordCount($conn,$sql)>0 ) return true;

    return false;
}

//验证uid是否有用户。
function is_user(&$conn,  &$u   )
{  
    $strsql="select * from tb_user where uid=$u  "; 
 
	if(getRecordCount($conn,  $strsql )>0)
	{  
		return true; 
	}

    return false;
}




	//http://192.168.1.100/s/addfriend.php?from=22&to=23&desc=xxx

    // from 发送content聊天 to 

    //参数验证
    if($uid==NULL || $to==NULL ||  $desc==NULL ||  strlen($desc) <2 ){
        $ret->code=-1; 
		$ret->desc="no param"; 
		die( json_encode($ret) );  
    }
	
	if($uid==  $to ){
        $ret->code=-1; 
		$ret->desc=" can not add self"; 
		die( json_encode($ret) );  
    }
	
	//还有判断目标是否存在！！
	if(is_user($conn,$to)==false)
	{
		$ret->code=0; 
		$ret->desc="not exist user:".$to; 
		die( json_encode($ret) );  
	}

	//还要验证好友关系。。。
	if(is_friend($conn,$uid,$to))
	{
		$ret->code=0; 
		$ret->desc="already is friend"; 
		die( json_encode($ret) );  
	}

	 
	 

	 $strsql="select * from tb_addfriendreq where uid=$uid and target=$to"; 
	 //还要判断是否已经请求过
	if(getRecordCount($conn,  $strsql )>0)
	{  
		$ret->code=0; 
		$ret->desc="already  request!!"; 
		die( json_encode($ret) );  
		return true; 
	}

 
	
	//保存一次请求。
		$s2="insert into  tb_addfriendreq  (uid,target,memo,createTime) values ($uid,$to,'$desc',now() ); ";
		
		//echo $s2;

		$jb->code=0;

		//执行
		mysql_query($s2, $conn)  or die(  json_encode($jb) );

		mysql_close();

        // echo "   $s2" , mysql_affected_rows() ;

           
        $t2 = microtime(true);
     
		$jb->code=1;
        $jb->test=  "请求已发出，ok ,耗时".round($t2-$t1,6)."秒"; 
        echo json_encode($jb);

 

		
	//还要更新对方的会话表。插入or更新。 
	$strsql="select * from tb_session where uid=$to and friendID=$uid  "; 

	// 执行sql查询
	$result=mysql_query($strsql, $conn);
	   
	$rows=mysql_fetch_assoc($result);
	if(!$rows)
	{
		 
			//不存在，
		$strsql="insert  into tb_session (uid , friendID , lastContent , lastTime ,state，type ) values( $to ,  $from , '$content' ,now() , -1 ,2) "; 

		// echo $strsql;

		mysql_query($strsql, $conn);//   or die(  json_encode($jb) );
		 
	}


?>
